<template>
	<view class="image-list-wrapper">
		<view :style="{width: boxWidth + 'rpx', height: boxWidth + 'rpx' }" class="image-list-item" v-for="(item, index) in imageList" :key="index">
			<image mode="aspectFill" @click="previewImage(index)" :src="item"></image>
			<view class="clear" @click="removeImg(index)">x</view>
		</view>
		<view :style="{width: boxWidth + 'rpx', height: boxWidth + 'rpx' }" class="upload-wrapper" v-if="imageList.length < max" @click="onuploadClick">
			<!-- <view class="add">
				+
			</view> -->
			<view class="add" :style="{width: boxWidth + 'rpx', height: boxWidth + 'rpx' }">
				<image src="/static/icon/8.png" mode=""></image>
			</view>
		</view>
		<canvas :style="{width: drawWidth+'px', height: drawHeight+'px',position: 'absolute', zIndex: '-1', left: '-10000rpx', top:' -10000rpx'}"
		 canvas-id="firstCanvas"></canvas>
		<image style="visibility: hidden;position: absolute;" ref='rawImage' @load="onImageLoad" :src="src" mode="aspectFit"></image>
		<!-- <image ref='compressedImage' :src="src1" mode="aspectFit"></image> -->
	</view>
</template>

<script>
	export default {
		name: "MyUploader",
		components: {},
		props: {
			boxWidth: {
				type: Number,
				default: 220
			},
			value: {
				type: Array,
				default: () => []
			},
			//最多上传几个文件
			max: {
				type: Number,
				default: 3,
			},
			//大于100K 需要压缩
			compressSize: {
				type: Number,
				default: 102400
			},
			needCompress: {
				type: Boolean,
				default: true
			},
			//默认压缩后宽度400px
			drawWidth: {
				type: Number,
				default: 300
			}
		},
		data() {
			return {
				src: '',
				src1: '',
				drawHeight: null,
				//原始图片宽高
				rawWidth: null,
				rawHeight: null,
				imageList: [],
				img: {},
				fileIds: [],
				isFromFather:true
			};
		},
		watch:{
			value(newVal,oldVal){
				// console.log('从父组件传入的值',newVal)
					if (this.isFromFather&& JSON.stringify(newVal)!= JSON.stringify(oldVal)) {
						this.downLoadFiles(newVal)
					} else {
						this.isFromFather = true
					}	
			}
		},
		onReady() {

		},
		methods: {
			onuploadClick() {
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album", "camera"], //从相册选择
					success: (res) => {
						console.log('点击上传',res)
						this.src = res.tempFilePaths[0]
						this.img = res.tempFiles[0]
					},
				});
			},
			//图片加载后，压缩
			async onImageLoad(e) {
				// console.log(e)
				let that = this
				this.rawWidth = e.target.width;
				this.rawHeight = e.target.height;

				this.drawHeight = this.drawWidth * this.rawHeight / this.rawWidth;
				// console.log(this.rawWidth, this.rawHeight, this.drawWidth, this.drawHeight)
				//需要压缩，并且图片大小超过compressSize
				console.log('图片大小:', this.img.size)
				console.log(this.needCompress,this.compressSize)
				//&& this.img.size > this.compressSize
				if (this.needCompress ) {
					// console.log('this.img', this.img)
					try {
						//获取压缩后的图
						let compressed = await this.compressImage(this.img)
						// console.log('compressed', compressed)
						that.imageList.push(compressed)
						let base64 = await this.urlTobase64(compressed);
						// console.log(base64)
						let fileId = await this.uploadFile(base64)
						this.fileIds.push(fileId)
						console.log('上传后的数组', this.fileIds)
						this.isFromFather = false	
						this.$emit('input', this.fileIds)
					} catch (e) {
						//TODO handle the exception
						// console.log(e)
					}

				}
			},
			compressImage(img) {
				console.log('压缩')
				return new Promise((resolve, reject) => {
					let that = this
					//小程序方法一定要加参数 this
					const ctx = uni.createCanvasContext('firstCanvas', this)
					//宽度为屏幕宽度，算出图片等比例的高度，

					ctx.drawImage(img.path, 0, 0, this.drawWidth, this.drawHeight);
					ctx.draw(false, setTimeout(function() {
						uni.canvasToTempFilePath({
							canvasId: 'firstCanvas',
							x: 0,
							y: 0,
							width: that.drawWidth,
							height: that.drawHeight,
							quality: 0.9, //最高质量，只通过尺寸放缩去压缩，画的时候都按最高质量来画
							success: (res) => {
								that.src1 = res.tempFilePath
								resolve(res.tempFilePath)
								// that.urlTobase64(res.tempFilePath)
							},
							fail: err => {
								reject(err)
							}
						}, that)
					}, 200));
				})

			},
			previewImage(index) {
				uni.previewImage({
					urls: this.imageList,
					current: index,
					longPressActions: {
						itemList: ["发送给朋友", "保存图片", "收藏"],
						success: function(data) {
							console.log("选中了第" + (data.tapIndex + 1) + "个按钮,第" + (data.index + 1) + "张图片");
						},
						fail: function(err) {
							console.log(err.errMsg);
						},
					},
				});
			},
			urlTobase64(url) {
				console.log('转base64')
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => { //成功的回调
							let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
							// this.dataList.picList.push(base64);
							// console.log(base64)
							console.log('转base64成功')
							let file = {
								fileData: base64,
								fileName: url
							};
							resolve(file)
							// this.uploadFile(file)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			// 上传文件
			uploadFile(file) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: "图片上传中",
						mask: true
					})
					// console.log(file)
					this.$http.post('common/file/upload', file).then(res => {
						console.log(res)
						if (res.code === 10000) {
							// this.baseArr.push(res.data.id)
							resolve(res.data.id)
							uni.hideLoading()
						}
					})
				})

			},
			removeImg(index) {
				this.imageList.splice(index, 1);
				let fileId = this.fileIds[index]
				this.fileIds.splice(index, 1);
				this.isFromFather = false
				this.$emit('input', this.fileIds)
				//删除服务器上的文件
				this.$http.post('common/file/delete', {
					id: fileId
				}).then(res => {

				})
			},
			setImages(fileIds) {
				console.log('传入', fileIds)
				this.downLoadFiles(fileIds)
			},
			downLoadFiles(fileIds) {
				let that = this
				fileIds.forEach(id => {
					console.log(id)
					this.$http.post('common/file/download', {
						id: id
					}).then(res => {
						console.log(res)
						if (res.code == 10000) {
							that.fileIds.push(id);
							that.imageList.push(res.data.fileData)
						}
					})
				})
			}
		},
	};
</script>
<style lang="less" scoped>
	.upload-wrapper {
		margin: 12rpx;
		width: 220rpx;
		height: 220rpx;
		// border: 1rpx solid #ccc;
		display: flex;
		justify-content: center;
		align-items: center;

		// .add {
		// 	font-size: 100rpx;
		// 	color: #ccc;
		// }
		.add {
			width: 220rpx;
			height: 220rpx;
			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.image-list-wrapper {
		display: flex;
		flex-wrap: wrap;
		// 
		padding-left: 4rpx;

		.image-list-item {
			margin: 12rpx;
			width: 220rpx;
			height: 220rpx;
			position: relative;

			image {
				// padding: 2rpx;
				border: 1rpx solid #ccc;
				max-width: 100%;
				max-height: 100%;
			}

			.clear {
				position: absolute;
				right: 0rpx;
				top: 0rpx;
				// color: grey;
				color: #fff;
				border: 1rpx solid grey;
				background: #000000;
				opacity: 0.34;
				height: 40rpx;
				font-size: 30rpx;
				width: 40rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				padding-bottom: 6rpx;
			}
		}
	}
</style>
